<script setup lang="ts">
import { computed, reactive, ref, watch } from 'vue';
import { addReport, fetchReportDetail, updateReport } from '@/service/api';
import { fetchDataSourceList } from '@/service/api';

defineOptions({
  name: 'ReportOperateDrawer'
});

interface Props {
  operateType: 'add' | 'edit';
  rowId?: number;
}

const props = defineProps<Props>();

interface Emits {
  (e: 'success'): void;
}

const emit = defineEmits<Emits>();

const visible = defineModel<boolean>('visible', { required: true });

const title = computed(() => (props.operateType === 'add' ? '新增报表' : '编辑报表'));

const loading = ref(false);
const formRef = ref<any>(null);

// 表单数据
const formModel = reactive<Api.DataPlatform.ReportEdit>({
  name: '',
  reportType: 'REPORT',
  datasourceId: undefined,
  chartConfig: '',
  layoutConfig: '',
  refreshInterval: 0,
  description: '',
  status: undefined, // 初始值为undefined，强制用户选择
  projectId: undefined,
  remark: ''
});

// 报表类型选项
const reportTypeOptions = [
  { label: '报表', value: 'REPORT' },
  { label: '仪表盘', value: 'DASHBOARD' },
  { label: '大屏', value: 'SCREEN' }
];

// 状态选项
const statusOptions = [
  { label: '禁用', value: 0 },
  { label: '启用', value: 1 }
];

// 数据源选项
const datasourceOptions = ref<Array<{ label: string; value: number }>>([]);

// 表单规则
const rules = {
  name: [{ required: true, message: '请输入报表名称', trigger: 'blur' }],
  reportType: [{ required: true, message: '请选择报表类型', trigger: 'change' }],
  status: [{ required: true, message: '请选择状态', trigger: ['change', 'blur'] }]
};

// 加载数据源列表
async function loadDatasources() {
  const { data } = await fetchDataSourceList({ pageNum: 1, pageSize: 1000 });
  if (data?.rows) {
    datasourceOptions.value = data.rows.map(item => ({
      label: item.name,
      value: item.id
    }));
  }
}

// 初始化表单
async function initForm() {
  if (props.operateType === 'edit' && props.rowId) {
    loading.value = true;
    try {
      const { data } = await fetchReportDetail(props.rowId);
      if (data) {
        Object.assign(formModel, data);
      }
    } finally {
      loading.value = false;
    }
  }
}

// 提交表单
async function handleSubmit() {
  await formRef.value?.validate();
  loading.value = true;
  try {
    if (props.operateType === 'add') {
      await addReport(formModel);
      window.$message?.success('新增成功');
    } else {
      await updateReport(formModel);
      window.$message?.success('更新成功');
    }
    visible.value = false;
    emit('success');
  } finally {
    loading.value = false;
  }
}

// 重置表单
function resetForm() {
  formRef.value?.restoreValidation();
  Object.assign(formModel, {
    name: '',
    reportType: 'REPORT',
    datasourceId: undefined,
    chartConfig: '',
    layoutConfig: '',
    refreshInterval: 0,
    description: '',
    status: undefined, // 改为undefined，强制用户选择
    projectId: undefined,
    remark: ''
  });
}

// 监听抽屉打开
watch(visible, val => {
  if (val) {
    loadDatasources();
    initForm();
  } else {
    resetForm();
  }
});
</script>

<template>
  <NDrawer v-model:show="visible" :width="720" :title="title">
    <NDrawerContent closable>
      <NForm ref="formRef" :model="formModel" :rules="rules" label-placement="left" :label-width="120">
        <NFormItem label="报表名称" path="name">
          <NInput v-model:value="formModel.name" placeholder="请输入报表名称" />
        </NFormItem>

        <NFormItem label="报表类型" path="reportType">
          <NSelect v-model:value="formModel.reportType" :options="reportTypeOptions" placeholder="请选择报表类型" />
        </NFormItem>

        <NFormItem label="数据源" path="datasourceId">
          <NSelect
            v-model:value="formModel.datasourceId"
            :options="datasourceOptions"
            placeholder="请选择数据源"
            clearable
          />
        </NFormItem>

        <NFormItem label="刷新间隔(秒)" path="refreshInterval">
          <NInputNumber
            v-model:value="formModel.refreshInterval"
            :min="0"
            placeholder="0表示不自动刷新"
            style="width: 100%"
          />
        </NFormItem>

        <NFormItem label="图表配置" path="chartConfig">
          <NInput
            v-model:value="formModel.chartConfig"
            type="textarea"
            placeholder="请输入图表配置JSON"
            :rows="6"
          />
        </NFormItem>

        <NFormItem label="布局配置" path="layoutConfig">
          <NInput
            v-model:value="formModel.layoutConfig"
            type="textarea"
            placeholder="请输入布局配置JSON"
            :rows="6"
          />
        </NFormItem>

        <NFormItem label="描述" path="description">
          <NInput v-model:value="formModel.description" type="textarea" placeholder="请输入描述" :rows="3" />
        </NFormItem>

        <NFormItem label="状态" path="status">
          <NRadioGroup v-model:value="formModel.status">
            <NSpace>
              <NRadio v-for="item in statusOptions" :key="item.value" :value="item.value">
                {{ item.label }}
              </NRadio>
            </NSpace>
          </NRadioGroup>
        </NFormItem>

        <NFormItem label="备注" path="remark">
          <NInput v-model:value="formModel.remark" type="textarea" placeholder="请输入备注" :rows="2" />
        </NFormItem>
      </NForm>

      <template #footer>
        <NSpace justify="end">
          <NButton @click="visible = false">取消</NButton>
          <NButton type="primary" :loading="loading" @click="handleSubmit">确定</NButton>
        </NSpace>
      </template>
    </NDrawerContent>
  </NDrawer>
</template>
